import 'package:flutter/material.dart';
import 'package:flutter_duqin/components/article_card.dart';
import 'package:flutter_duqin/components/singer_card.dart';
import 'package:flutter_duqin/components/song_card.dart';
import 'package:flutter_duqin/components/video_card.dart';
import 'package:flutter_duqin/models/article_model.dart';
import 'package:flutter_duqin/models/recommend_interface.dart';
import 'package:flutter_duqin/models/song_model.dart';
import 'package:flutter_duqin/models/user_model.dart';
import 'package:flutter_duqin/models/video_model.dart';
import 'package:flutter_duqin/services/recommend_service.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class RecommendPage extends StatefulWidget {
  const RecommendPage({Key? key}) : super(key: key);

  @override
  State<RecommendPage> createState() => _RecommendPageState();
}

class _RecommendPageState extends State<RecommendPage>
    with AutomaticKeepAliveClientMixin {
  final EasyRefreshController _controller = EasyRefreshController();
  List<RecommendInterface> _recommendList = [];
  bool error = false;
  String errorMsg = "";

  @override
  void initState() {
    super.initState();

    _getRecommends();
  }

  // 获取数据
  Future _getRecommends({bool push = false}) async {
    try {
      // 获取数据
      List<dynamic> result =
          await RecommendService.getRecommends(page: 1, limit: 10);

      // 将数据转为实体类
      List<RecommendInterface> recommendList = result.map((item) {
        if (item['item1'] == "songEntity") {
          return SongItem.fromJson(item["item2"]);
        } else if (item['item1'] == "articleEntity") {
          return ArticleItem.fromJson(item["item2"]);
        } else if (item['item1'] == "videoEntity") {
          return VideoItem.fromJson(item["item2"]);
        } else {
          return UserItem.fromJson(item["item2"]);
        }
      }).toList();

      setState(() {
        print('setState...');
        if (push) {
          _recommendList.addAll(recommendList);
        } else {
          _recommendList = recommendList;
        }
      });
    } catch (e) {
      print(e.toString());
      setState(() {
        error = true;
        errorMsg = e.toString();
      });
    }
  }

  // 下拉刷新
  Future _onRefresh() async {
    await _getRecommends();
    _controller.finishRefresh();
    _controller.resetLoadState();
  }

  // 上拉加载
  Future _onLoad() async {
    await _getRecommends(push: true);
    _controller.finishLoad();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return EasyRefresh(
      controller: _controller,
      header: ClassicalHeader(),
      footer: ClassicalFooter(),
      enableControlFinishLoad: true,
      enableControlFinishRefresh: true,
      onRefresh: _onRefresh,
      onLoad: _onLoad,
      child: ListView.builder(
        itemCount: _recommendList.length,
        itemBuilder: (context, index) {
          Widget widget = _getWidgetByInterface(_recommendList[index]);
          return Column(
            children: [
              const SizedBox(
                height: 8,
              ),
              widget,
            ],
          );
        },
      ),
    );
  }

  Widget _getWidgetByInterface(RecommendInterface widgetItem) {
    if (widgetItem is SongItem) {
      return _columnBox(SongCard(songItem: widgetItem));
    } else if (widgetItem is ArticleItem) {
      return _columnBox(ArticleCard(articleItem: widgetItem));
    } else if (widgetItem is VideoItem) {
      return _columnBox(VideoCard(videoItem: widgetItem));
    } else if (widgetItem is UserItem) {
      return _columnBox(Container(
        padding: const EdgeInsets.only(top: 18, left: 18, right: 18),
        color: Colors.white,
        child: SingerCard(singerItem: widgetItem),
      ));
    } else {
      return const SizedBox.shrink();
    }
  }

  Widget _columnBox(Widget card) {
    return Column(
      children: [
        const SizedBox(
          height: 8,
        ),
        card,
      ],
    );
  }

  @override
  bool get wantKeepAlive => true;
}
